package com.example.blog.utils;

import org.junit.jupiter.api.Test;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

public class SecurityUtils {
    //进行加密解密操作
    public static void main(String[] args) throws UnsupportedEncodingException {
        //md5加密
        System.out.println(DigestUtils.md5DigestAsHex("123456".getBytes("UTF-8")));//生成16进制,32位
        //盐值
        System.out.println(UUID.randomUUID());//UUID就是盐值,但是直接生成的字符串内有 - ,可以通过方法进行去掉
        System.out.println(UUID.randomUUID().toString().replace("-",""));//没有 - 了
    }

    //加密
    @Test
    void encrypt() throws UnsupportedEncodingException {
        String password = "admin";
        String salt = UUID.randomUUID().toString().replace("-","");
        //md5(salt+password)
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        //数据库存储 盐值+密文
        String sqlPassword = salt+secretString;
        System.out.println(sqlPassword);
    }

    @Test
    void verify() throws UnsupportedEncodingException {
        String inputPassword = "123456";
        String sqlPassword = "edc898009ed6482296a808bf0c147663422bd8ed61bcc73590d8712f2aa0dbed";
        String salt = sqlPassword.substring(0,32);
        String secretString = DigestUtils.md5DigestAsHex((salt+inputPassword).getBytes("UTF-8"));
        String sqlPassword2 = salt+secretString;
        if (sqlPassword2.equals(sqlPassword)){
            System.out.println("密码正确");
        }else {
            System.out.println("密码错误");
        }
    }
}
